package com.enba.boot.es.manager;

import java.util.List;
import java.util.stream.Collectors;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.stereotype.Component;

@Component
public class ElasticsearchPageHelper<T> {

  private final ElasticsearchRestTemplate elasticsearchRestTemplate;

  public ElasticsearchPageHelper(ElasticsearchRestTemplate elasticsearchRestTemplate) {
    this.elasticsearchRestTemplate = elasticsearchRestTemplate;
  }

  /**
   * 分页查询
   *
   * @param query 查询条件
   * @param pageable 分页信息
   * @param targetClass 目标实体类
   * @return 分页结果
   */
  public Page<T> search(NativeSearchQuery query, Pageable pageable, Class<T> targetClass) {
    // 设置分页参数
    query.setPageable(pageable);

    // 执行查询
    SearchHits<T> searchHits = elasticsearchRestTemplate.search(query, targetClass);

    // 获取查询结果
    List<T> content =
        searchHits.getSearchHits().stream().map(SearchHit::getContent).collect(Collectors.toList());

    // 获取总记录数
    long totalHits = searchHits.getTotalHits();

    // 返回分页结果
    return new PageImpl<>(content, pageable, totalHits);
  }

  /**
   * 构建分页请求
   *
   * @param page 当前页码（从 0 开始）
   * @param size 每页大小
   * @return 分页请求对象
   */
  public Pageable buildPageRequest(int page, int size) {
    return PageRequest.of(page, size);
  }
}
